<?php
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;
use Qcloud\Sms\SmsSingleSender;

/*
 * 注释方法
 * 快速生成动作列表
switch($this->getRequestAction()){
    case  $this::REQUEST_ACTION_ADD:{

    };break;
    case  $this::REQUEST_ACTION_DELETE:{

    };break;
    case  $this::REQUEST_ACTION_UPDATE:{

    };break;
    case  $this::REQUEST_ACTION_LIST:{

    };break;
    case  $this->REQUEST_ACTION_DETAIL:{

    };break;
}
*/


class SubsystemController extends CloudControllerBase
{

    /******************************    子系统管理    ***********************************************************/

    //添加子系统
    public function addAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        switch ($this->getRequestAction()) {
            case  $this::REQUEST_ACTION_ADD: {
                $validation = new Phalcon\Validation();
                $validation->add('system_name', new StringLength(array('max' => 128, 'min' => 1, 'messageMaximum' => '名称在128个字符之间', 'messageMinimum' => '请填写系统名称')));

                $this->checkRequest($validation, $this->request->getPost());
                $systemName = $this->getPost("system_name");
                $systemLogo = $this->getPost("system_logo_url");
                $systemTitle = $this->getPost("system_title");
                $systemId = $this->insert("subsystem_info", array(
                    "system_name" => $systemName,
                    "system_logo_url" => $systemLogo,
                    "system_title" => $systemTitle
                ));
                if ($systemId > 0) {
                    $this->saveOperationLog("添加子系统", "添加子系统 system_name:$systemName id:$systemId");
                    $this->returnSuccess("添加成功");
                } else {
                    $this->returnError("添加失败");
                }
            };
                break;
        }
    }


    //子系统列表,删除
    public function listAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限错误", "操作权限错误");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {

                if ($this->isSubsystemExistUsers()) {
                    $this->returnError("错误,系统下面存在用户,无法删除对应系统");
                }
                if ($this->isSubsystemExistPlanes()) {
                    $this->returnError("错误,系统下面存在飞机,无法删除对应系统");
                }
                $this->generateDeleteData(array(
                    "table" => "subsystem_info",
                    "paramList" => array(
                        ["id", "="],
                        ["batch_keys", "in", "(", ")", "id"],
                        ["system_name", "like", "%", "%"],
                        ['system_title', 'like', '%', '%'],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),
                    "where" => " not id=1",
                ));

            };
                break;
            case  $this::REQUEST_ACTION_LIST: {

                $tableName = "(SELECT s.*,total,plane_total from subsystem_info as s
left join  (SELECT system_id,count(system_id) total from bind_user_system GROUP by system_id) as temp on temp.system_id=s.id
left join  (SELECT system_id,count(plane_id) plane_total from bind_plane_system GROUP by system_id) as ok on ok.system_id=s.id
)";

                $this->postQueryByPage(array(
                    "id" => "ID",
                    "system_name" => "内部名称",
                    "system_title" => "系统名称",
                    "created_at" => "创建时间",
                    "total" => "人员总数",
                    "plane_total" => "飞机总数"
                ), $tableName, array(
                    ["system_name", "like", "%", "%"],
                    ['system_title', 'like', '%', '%'],
                    ['created_at_start', '>=', '', '', "created_at"],
                    ['created_at_end', '<=', '', '', "created_at"]
                ), "created_at desc", "id");


            };
                break;
            default: {
                //查询相关的动作
                $roleData = $this->fetchAll("select id,user_role_name from user_role ");
                $this->view->setVars(array("roleData" => json_encode($roleData)));
            };
                break;
        }
    }

    //子系统详情
    public function detailAction()
    {

        $systemId = $this->getPost("id");
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_DETAIL: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "id为空"
                    )
                ));
                $sql = "SELECT * FROM subsystem_info WHERE id=$systemId";
                $systemData = $this->fetchOne($sql);
                $this->returnJson($systemData);
            }
                break;

            case $this::REQUEST_ACTION_UPDATE: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "id为空"
                    )
                ));
                $base_img = $this->getPost("system_data");
                $data = array();
                if ($base_img) {
//                    array_push($fieldList, "system_data");
                    $uploadRet = $this->uploadIconCos($base_img, $systemId);
                    if ($uploadRet['message'] != 0) {
                        return $this->returnError("上传失败");
                    } else {
                        $data['system_logo_url'] = $uploadRet;
                    }
                }
                $data['system_title'] = $this->getPost("system_title");
                $data['system_name'] = $this->getPost("system_name");
                $data['created_at'] = $this->getPost('created_at');
                $data['plane_limit']=$this->getPost("plane_limit");
                $result = $this->update("subsystem_info", $data, 'id=' . $systemId);
//                $returnData['imgUrl'] = $uploadRet;
                return $this->returnSuccess("更新成功");
//                $fieldList = array("system_name", "system_title", "created_at");
//                if ($this->getPost("system_data")){
//                    array_push($fieldList, "system_data");
//                }
//                $this->generateUpdateData(array(
//                    "table" => "subsystem_info",
//                    "fieldList" => $fieldList,
//                    "where" => " id=$systemId"
//                ));
            }
                break;

            default: {

            }
                break;
        }

    }


    //子系统内更改系统信息
    public function changeInfoAction()
    {
        $user = $this->getMonitorLoginUser();
        $systemId = $user->subsystemId;
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_DETAIL: {
                $sql = "SELECT * FROM subsystem_info WHERE id=$systemId";
                $systemData = $this->fetchOne($sql);
                $this->returnJson($systemData);

            }
                break;

            case $this::REQUEST_ACTION_UPDATE: {
//                $fieldList = array("system_name", "system_title");
                $base_img = $this->getPost("system_data");
                $data = array();
                if ($base_img) {
//                    array_push($fieldList, "system_data");
                    $uploadRet = $this->uploadIconCos($base_img, $systemId);
                    if ($uploadRet['message'] != 0) {
                        return $this->returnError("上传失败");
                    } else {
                        $data['system_logo_url'] = $uploadRet;
                    }
                }
                $data['system_title'] = $this->getPost("system_title");
                $result = $this->update("subsystem_info", $data, 'id=' . $systemId);
                return $this->returnSuccess("更新成功");
//                $this->generateUpdateData(array(
//                    "table" => "subsystem_info",
//                    "fieldList" => $fieldList,
//                    "where" => " id=$systemId"
//                ));
            }
                break;

            default: {

            }
                break;
        }
    }


    /******************************    子系统--->用户管理    ***********************************************************/


    //添加用户记录
    public function addUserLogAction()
    {
        switch ($this->getRequestAction()) {

            case  $this::REQUEST_ACTION_DELETE: {

            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $user = $this->getMonitorLoginUser();
                $systemId = $user->subsystemId;
                $tableName = "(SELECT system.*,origin.phone as origin_phone,target.phone as target_phone 
                FROM system_add_user as system 
                LEFT JOIN user as origin on origin.id=system.user_id 
                left join user as target on target.id=system.applyUser_id 
                where system.system_id=$systemId)";
                $this->postQueryByPage(array(
                    "type" => "操作类型",
                    "origin_phone" => "操作用户手机",
                    "target_phone" => "目标用户手机",
                    "created_at" => "发送时间",
                    "receive_at" => "回复时间",
                    "status" => "当前状态",
                ), $tableName, array(
                    ["origin_phone", "like", "%", "%"],
                    ["target_phone", "like", "%", "%"],
                    ["created_at_start", ">=", '', '', "created_at"],
                    ["created_at_end", "<=", '', '', "created_at"],
                    ["status", "=", "", ""]
                ));

            };
                break;
        }

    }

    //用户监控列表
    public function monitorListAction()
    {
        switch ($this->getRequestAction()) {
            case  $this::REQUEST_ACTION_DELETE: {

                $filterList = json_decode($this->getPost("filter_list"), true);
                $userId = $filterList["user_id"];
                if ($userId &&$this->isMonitorSubsystemAdminUser()) {
                    $user = $this->getmonitorLoginUser();
                    $sql = "delete from bind_user_system where system_id=$user->subsystemId and user_id=$userId";
                    $this->execute($sql);
                    $this->returnSuccess("删除成功");
                }else{
                    $this->returnError("user_id为空");
                }
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                if ($this->isMonitorSubsystemAdminUser()) {
                    $user = $this->getMonitorLoginUser();
                    $systemId = $user->subsystemId;
                    $tableName = "(select s.*,u.phone as login_phone,r.user_role_name from bind_user_system as s
                    left join user_role as r on r.id=s.user_role_id 
              left join user as u on u.id=s.user_id where system_id=$systemId)";
                    $this->postQueryByPage(array(

                        "user_id" => "用户ID",
                        "login_phone" => "登录手机号",
                        "real_name" => "姓名",
                        "contact_info" => "联系方式",
                        "dept_name" => "部门名称",
                        "user_role_name" => "用户角色",
                        "created_at" => "加入时间"
                    ), $tableName, array(
                        ["login_phone", "like", "%", "%"],
                        ["created_at_start", ">=", "", "", "created_at"],
                        ["created_at_end", "<=", "", "", "created_at"],
                    ), "created_at desc", "user_id");
                } else {
                    $this->returnError("操作权限错误");
                }
            };
                break;
            case  $this->REQUEST_ACTION_DETAIL: {

            };
                break;
        }
    }

    //用户详情
    public function monitorDetailAction()
    {
        $userid = intval($this->getQuery("userid"));
        $tableName = "(select s.*,u.phone as login_phone,sub.system_name from bind_user_system as s
              left join user as u on u.id=s.user_id
              left join subsystem_info as sub on sub.id=s.system_id 
              where s.user_id=$userid)";
        $this->generateDetailData(array(
            "table" => $tableName,
            "column" => array(
                ["login_phone", "登录手机号", "disabled"],
                ["created_at", "加入时间", "disabled"],
                ["system_name", "所属系统", "disabled"],
                ["real_name", "姓名", ""],
                ["contact_info", "联系方式", ""],
                ["dept_name", "部门名称", ""],
                ["id", "", "", false],
            ),
            "title" => "ID",
            "titleKey" => "id",
            "keyName" => "id",
            "where" => " user_id=$userid",
        ));
    }

    //用户更新
    public function doMonitorUpdateAction()
    {
        $validation = new Phalcon\Validation();
        $validation->add('id', new PresenceOf(array('message' => 'id为空')));
        $this->checkRequest($validation, $this->request->getPost());
        $systemId = $this->getPost("id");
        $this->generateUpdateData(array(
            "table" => "bind_user_system",
            "fieldList" => array("real_name", "contact_info", "dept_name"),
            "where" => " id=$systemId"
        ));
    }

    /**
     * 添加用户
     */
    public function addUserAction()
    {

    }

    /**
     * 添加用户动作
     */
    public function doAddUserAction()
    {
        $user = $this->getMonitorLoginUser();

        // 获得request
        $validation = new Phalcon\Validation();
        $validation->add('phone', new RegexValidator(array('pattern' => '/^[0-9]{11}$/', 'message' => '手机号码格式不正确')));

        $this->checkRequest($validation, $this->request->getPost());

        $expire = $this->redisExpire['sms'];
        // 获得request
        $phone = $this->getPost("phone");

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "adduser phone:$phone, expire:$expire\r\n", FILE_APPEND);
        // 检测用户是否存在
        $sql = "SELECT * FROM user where phone = '$phone'";
        $applyUser = $this->fetchOne($sql);
        if (!$applyUser) {
            $this->returnError('用户不存在!');
        }

        $sql = "SELECT * FROM bind_user_system where user_id = {$applyUser['id']}";
        $bind = $this->fetchOne($sql);
        if ($bind) {
            $this->returnError('用户已绑定过子系统!');
        }

        if ($this->redis->exists("system-add-$phone")) {
            // 如果redis中存在验证码
            $validate = $this->redis->get("system-add-$phone");
            // 检测验证码发送周期
            if ($this->redis->ttl("system-add-$phone") > $expire - 29) {
                $this->returnInfo('至少需要30秒才能重新发送验证码。');
            } else {
                $this->redis->setex("system-add-$phone", $expire, $validate);
            }
        } else {
            // 如果redis中不存在，那么创建验证码和时间戳
            $validate = mt_rand(1000, 9999);
            $this->redis->setex("system-add-$phone", $expire, $validate);
        }

        if ($user->userRoleId == 1) {
            $sql = "SELECT user_role_name FROM user_role where id = 1";
            $adminName = $this->fetchColumn($sql);
        } else if ($user->userRoleId == 2) {
            $sql = "select nickname from user where id = " . $user->userId;
            $adminName = $this->fetchColumn($sql);
        } else {
            $this->returnError("权限不足");
        }

        $sql = "SELECT s.id,system_name from bind_user_system as u LEFT JOIN subsystem_info as s on u.system_id=s.id WHERE u.user_id=" . $user->userId;
        $systemInfo = $this->fetchOne($sql);

        if ($systemInfo) {
            $sql = "select * from system_add_user where system_id={$systemInfo['id']} and applyUser_id={$applyUser['id']} and type=1";
            $system = $this->fetchOne($sql);
            if (!$system) {
                // 发送短信
//                 $result = $this->sendValidateSmsByInvoice($phone, $validate);
//                 $result = $this->sendAddUserValidateSms($phone, $adminName, $systemInfo['system_name']);
//                 【飞马机器人】#adminName# 希望把你加入到 #systemName#  中去，回复TYTJ,添加到该系统中去回T退订
//                 $content = "【飞马机器人】" . $adminName . "希望把你加入到" . $systemInfo['system_name'] . "中去，回复TYTJ,添加到该系统中去";
//                $content = "【飞马机器人】" . $adminName . " 希望把你加入到 " . $systemInfo['system_name'] . "  中去，回复TYTJ,添加到该系统中去回T退订";
                $content = "【飞马机器人】" . $adminName . " 希望把你加入到 " . $systemInfo['system_name'] . "  中去，请于" . ($expire/60) . "分钟内回复TYTJ，添加到该系统中去回T退订";
                $content = "【飞马机器人】" . $adminName . " 希望把你加入到 " . $systemInfo['system_name'] . "  中去，请于" . ($expire/60) . "分钟内回复TYTJ，添加到该系统中去";
                $result = $this->sendSmsContent($phone, $content);

//                 $result = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
//                 $result = json_decode($result,true);

                if ($result['code'] != '0') {
                    file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($result) . " \r\n", FILE_APPEND);
                    $this->returnResponse(4, $result ['errmsg'], $result);
                }

                $foreignId = $this->insert("system_add_user", array(
                    "user_id" => $user->userId,
                    "system_id" => $systemInfo['id'],
                    "created_at" => date("Y-m-d H:i:s"),
                    "applyUser_id" => $applyUser['id'],
                    "type" => 1,
                    "status" => 0));

                $this->insert("send_sms", array(
                    "user_id" => $user->userId,
                    "sms_id" => $result['sid'],
                    "ext" => $result['ext'],
                    "phone" => $phone,
                    "foreign_id" => $foreignId,
                    "content" => $content,
                    "type" => 1));

                $this->returnSuccess("发送成功");
            } else if ($system['status'] == '2') {
                $this->returnError("用户已添加");
            } else {
//                 $result = $this->sendValidateSmsByInvoice($phone, $validate);
//                 $content = "【飞马机器人】" . $adminName . "希望把你加入到" . $systemInfo['system_name'] . "中去，回复TYTJ,添加到该系统中去";
//                $content = "【飞马机器人】" . $adminName . " 希望把你加入到 " . $systemInfo['system_name'] . "  中去，回复TYTJ,添加到该系统中去回T退订";
//                 $content = "【飞马机器人】" . $adminName . " 希望把你加入到 " . $systemInfo['system_name'] . "  中去，请于" . ($expire/60) . "分钟内回复TYTJ，添加到该系统中去回T退订";
                $content = "【飞马机器人】" . $adminName . " 希望把你加入到 " . $systemInfo['system_name'] . "  中去，请于" . ($expire/60) . "分钟内回复TYTJ，添加到该系统中去";
                $result = $this->sendSmsContent($phone, $content);

//                 $result = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
//                 $result = json_decode($result,true);

                if ($result['code'] != '0') {
                    file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($result) . " \r\n", FILE_APPEND);
                    $this->returnResponse(4, $result ['errmsg'], $result);
                }

                $this->update("system_add_user", array(
                    "user_id" => $user->userId,
                    "created_at" => date("Y-m-d H:i:s"),
                    "receive_at" => null,
                    "status" => 0),
                    'id=' . $system['id']);

                $this->insert("send_sms", array(
                    "user_id" => $user->userId,
                    "sms_id" => $result['sid'],
                    "ext" => $result['ext'],
                    "phone" => $phone,
                    "foreign_id" => $system['id'],
                    "content" => $content,
                    "type" => 1));

                $this->returnSuccess("发送成功");
            }
        } else {
            $this->returnError("子系统不存在");
        }

    }

    /******************************    后台批量管理权限接口   ***********************************************************/


    public function undispatchPlaneAction(){

        if($this->isMonitorAdminUser())
        {
            $uasId = $this->getPost("uas_id");
            $sysId = $this->getPost("system");
            if(!empty($uasId)){
                $where=" and uas_serial_id like '%$uasId%'";
            }
            $sql= "
SELECT
	p.*, b.system_id
FROM
	(
		SELECT
			p.id,
			p.uas_serial_id,
			m. NAME model_name
		FROM
			plane p
		LEFT JOIN plane_model m ON p.planeModel_id = m.id
	) p
LEFT JOIN bind_plane_system b ON b.plane_id = p.id
WHERE
	(b.id IS NULL OR b.system_id=$sysId) $where
ORDER BY
	uas_serial_id DESC";
            $data=$this->fetchAll($sql);
            $this->returnJson($data);
        }else{
            $this->returnAuthError();
        }
    }

    public function batchAddMonitorPlaneAction(){
        if($this->isMonitorAdminUser())
        {

            $planes = $this->getPost("planes");
            $sysId = $this->getPost("system");
            $userId=$this->getMonitorLoginUser()->userId;
            //判断需要添加的飞机数量
            //判断飞机是否已经被添加到系统中
            $curCount=intval($this->fetchColumn("select count(*) from bind_plane_system where system_id=$sysId"));
            $planeLimit=intval($this->fetchColumn("select plane_limit from subsystem_info where id=$sysId"));
            if($planeLimit>=count($planes)){
                $deleteSql="delete from bind_plane_system where system_id=$sysId";
                $this->execute($deleteSql);
                $this->saveDeleteLog("bind_plane_system","","system_id=$sysId");
                foreach ($planes as $planeItem) {
                    //判断该飞机是否在系统中国呢
                    $id=$planeItem["id"];

                    $existCount=$this->fetchColumn("select count(*) from bind_plane_system where plane_id=$id ");
                    if(intval($existCount)<=0){
                        $this->insert("bind_plane_system",array(
                            "plane_id"=>$id,
                            "system_id"=>$sysId,
                            "user_id"=>$userId
                        ),true);
                    }
                }
                $this->returnSuccess("操作成功");
            }else{
                $this->returnError("当前系统只能添加飞机数量上限为 $planeLimit 架");
            }
            $this->returnJson($curCount);
        }else{
            $this->returnAuthError();
        }
    }


    //获取未分配的人员列表
    public function undispatchUsersAction()
    {

        if ($this->isMonitorAdminUser()) {
            $phone = $this->getPost("phone");
            $sysId = $this->getPost("system");
            if (empty($sysId)) {
                $this->returnError("系统ID为空");
            }
            $where = "";
            if (!empty($phone)) {
                $where .= " and  (phone like '%" . $phone . "%' or nickname like '%" . $phone . "%')";
            }
            $sqlUser = "SELECT * from (
SELECT user.id ,user.phone,s.system_id,s.user_role_id,user.nickname from user
LEFT JOIN bind_user_system as s on s.user_id=user.id)
as temp
WHERE ( system_id is null or system_id=$sysId )" . $where;
            $userData = $this->fetchAll($sqlUser);
            $this->returnJson($userData);
        } else {
            $this->returnError("权限不足");
        }

    }

    //更新绑定用户系统
    public function updateBindUserSystemAction()
    {
        if ($this->isMonitorAdminUser()) {
            $requestList = $this->getPost("updateInfo");
            $systemId = $this->getPost("system");
            $delteAll = $this->getPost("deleteAll");
            if (empty($requestList) || empty($systemId)) {
                if (!empty($systemId) && !empty($delteAll) && $delteAll == 1) {
                    $this->execute("delete from bind_user_system where system_id=$systemId");
                    $this->returnSuccess("更新成功");
                } else {
                    $this->returnError("参数不合法");
                }

            } else {
                $allInfo = "select system_id,user_id,user_role_id from bind_user_system where system_id=$systemId";
                $data = $this->fetchAll($allInfo);
                $addInfo = array();//添加集合
                $deleteInfo = array();//删除集合

                for ($i = 0; $i < count($requestList); $i++) {
                    $isNeedAdd = true;
                    for ($j = 0; $j < count($data); $j++) {
                        $requestUserId = $requestList[$i]["user_id"];
                        $targetUserId = $data[$j]["user_id"];

                        if ($targetUserId == $requestUserId) {
                            $isNeedAdd = false;
                            break;
                        }
                    }
                    if ($isNeedAdd) {
                        $itemRoleId = $requestList[$i]["user_role_id"];
                        $itemUserId = $requestList[$i]["user_id"];
                        array_push($addInfo, "insert into bind_user_system (system_id,user_id,user_role_id)VALUES ($systemId,$itemUserId,$itemRoleId)");
                    }
                }
                for ($j = 0; $j < count($data); $j++) {
                    $isNeedDelete = true;
                    $targetUserId = $data[$j]["user_id"];
                    for ($i = 0; $i < count($requestList); $i++) {
                        if ($targetUserId == $requestList[$i]["user_id"]) {
                            $isNeedDelete = false;
                            break;
                        }
                    }
                    if ($isNeedDelete) {
                        array_push($deleteInfo, "delete from bind_user_system where system_id=$systemId and user_id=$targetUserId");
                    }
                }
                $this->begin();
                foreach ($addInfo as $item) {
                    $this->execute($item);
                }
                foreach ($deleteInfo as $item) {
                    $this->execute($item);
                }
                $this->commit();

                $this->returnSuccess("更新成功");
            }

        }
    }


    //子系统下面,是否存在用户
    private function isSubsystemExistUsers()
    {
        $whereAppend = $this->generateQueryWhereStr(array(
            ["id", "="],
            ["batch_keys", "in", "(", ")", "id"],
            ["system_name", "like", "%", "%"],
            ['system_title', 'like', '%', '%'],
            ['created_at_start', '>=', '', '', "created_at"],
            ['created_at_end', '<=', '', '', "created_at"]
        ));
        if ($whereAppend && !empty($whereAppend[0])) {
            $sql = "select count(*) as total from bind_user_system 
                where system_id in (select id from subsystem_info where $whereAppend[0])";

            $data = $this->dbQuery->fetchAll($sql, \Phalcon\Db::FETCH_ASSOC, $whereAppend[1]);
            for ($i = 0; $i < count($data); $i++) {
                if ($data[$i]["total"] > 0) {
                    return true;
                }
            }
        }
        return false;
    }

    private function isSubsystemExistPlanes()
    {
        $whereAppend = $this->generateQueryWhereStr(array(
            ["id", "="],
            ["batch_keys", "in", "(", ")", "id"],
            ["system_name", "like", "%", "%"],
            ['system_title', 'like', '%', '%'],
            ['created_at_start', '>=', '', '', "created_at"],
            ['created_at_end', '<=', '', '', "created_at"]
        ));
        if ($whereAppend && !empty($whereAppend[0])) {
            $sql = "select count(*) as total from bind_plane_system 
                where system_id in (select id from subsystem_info where $whereAppend[0])";
            $data = $this->dbQuery->fetchAll($sql, \Phalcon\Db::FETCH_ASSOC, $whereAppend[1]);
            for ($i = 0; $i < count($data); $i++) {
                if ($data[$i]["total"] > 0) {
                    return true;
                }
            }
        }
        return false;
    }


    /******************************    子系统--->用户权限分配   ***********************************************************/

    public function listAuthAction()
    {

        $adminId = MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN;
        $userListSql = "select b.*,u.nickname,u.phone,u.user_auth_menu,u.id as user_id from bind_user_system as b
left join user u on u.id=b.user_id
WHERE b.user_role_id=$adminId and b.system_id=1";
        $userList = $this->fetchAll($userListSql);

        $this->view->setVars(array("userList" => json_encode($userList),
            "menuList" => json_encode($this->defaultAuthMenu["admin"]),
            "curUserId" => $this->getMonitorLoginUser()->userId,
            "unableMenu" => "/subsystem/listAuth"
        ));
    }

    //更新权限
    public function updateAuthAction()
    {
        if ($this->isMonitorAdminUser()) {
            $user = $this->getMonitorLoginUser();
            $this->checkRequestParams(array(
                    array(
                        "key" => "auth_menu",
                        "type" => "presence",
                        "message" => "请提供权限"),
                    array(
                        "key" => "user_id",
                        "type" => "number",
                        'message' => 'user_id为空',
                    ),
                )
            );
            $userId = $this->getPost("user_id");
            $authMenu = $this->getPost("auth_menu");
            $selectAll = $this->getPost("all");

            if ($selectAll) {
                $authMenu = "";
            }
            $this->update("user", array("user_auth_menu" => $authMenu), "id=$userId");

            //如果自己用户是自己的话,则应该更新当前自己的账号权限
            if ($user->userId == $userId) {
                $user->userAuthMenu = $authMenu;
            }
            $this->returnSuccess("更新成功");
        } else {
            $this->returnError("权限错误");
        }
    }

    /******************************    子系统--->飞机管理    ***********************************************************/

    //添加飞机
    public function addPlaneAction()
    {

    }

    public function addPlaneLogAction()
    {
        $user = $this->getMonitorLoginUser();
        $systemId = $user->subsystemId;
        switch ($this->getRequestAction()) {

            case  $this::REQUEST_ACTION_DELETE: {

            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $tableName = "(SELECT system.*,origin.phone as origin_phone 
                FROM system_add_plane as system 
                LEFT JOIN user as origin on origin.id=system.user_id 
                WHERE system.system_id=$systemId)";
                $this->postQueryByPage(array(
                    "type" => "操作类型",
                    "origin_phone" => "操作用户手机",
                    "created_at" => "发送时间",
                    "receive_at" => "回复时间",
                    "status" => "当前状态",
                ), $tableName, array(
                    ["origin_phone", "like", '%', '%'],
                    ["status", "=", '', ''],
                    ["created_at_start", ">=", '', '', "created_at"],
                    ["created_at_end", "<=", '', '', "created_at"]
                ));

            };
                break;
        }

    }

    /**
     * 添加飞机逻辑
     */
    public function doAddMonitorAction()
    {
        $user = $this->getMonitorLoginUser();

        // 获得request
//         $validation = new Phalcon\Validation ();
//         $validation->add ( 'phone', new RegexValidator ( array ( 'pattern' => '/^[0-9]{11}$/', 'message' => '手机号码格式不正确' ) ) );
//         $this->checkRequest ( $validation, $this->request->getPost () );

        $uasSerialId = $this->getPost("uas_serial_id", '', 'striptags');

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "addplane uasSerialId:$uasSerialId\r\n", FILE_APPEND);

        $expire = $this->redisExpire ['sms'];
        // 检测用户是否存在

        $sql = "SELECT s.id,system_name,plane_limit from bind_user_system as u LEFT JOIN subsystem_info as s on u.system_id=s.id WHERE u.user_id=" . $user->userId;
        $systemInfo = $this->fetchOne($sql);

        if ($systemInfo) {

            $sql = "SELECT count(id) as id FROM bind_plane_system where system_id = {$systemInfo['id']}";
            $planeCount = $this->fetchColumn($sql);

            if ($planeCount < $systemInfo['plane_limit']) {

                $sql = "SELECT * FROM plane where uas_serial_id = '$uasSerialId'";
                $plane = $this->fetchOne($sql);
                if (!$plane) {
                    $this->returnError('飞机不存在!');
                }

                if (empty($plane['phone'])) {
                    $this->returnError('电话号码不存在');
                }

                $sql = "SELECT * FROM bind_plane_system where plane_id = {$plane['id']}";
                $bind = $this->fetchOne($sql);
                if ($bind) {
                    $this->returnError('飞机已绑定过子系统!');
                }

                if ($this->redis->exists("bind-plane-{$plane['phone']}")) {
                    // 如果redis中存在验证码
                    $validate = $this->redis->get("bind-plane-{$plane['phone']}");
                    // 检测验证码发送周期
                    if ($this->redis->ttl("bind-plane-{$plane['phone']}") > $expire - 29) {
                        $this->returnInfo('至少需要30秒才能重新发送验证码。');
                    } else {
                        $this->redis->setex("bind-plane-{$plane['phone']}", $expire, $validate);
                    }
                } else {
                    // 如果redis中不存在，那么创建验证码和时间戳
                    $validate = mt_rand(1000, 9999);
                    $this->redis->setex("bind-plane-{$plane['phone']}", $expire, $validate);
                }

                if ($user->userRoleId == 1) {
                    $sql = "SELECT user_role_name FROM user_role where id = 1";
                    $adminName = $this->fetchColumn($sql);
                } else if ($user->userRoleId == 2) {
                    $sql = "select nickname from user where id = " . $user->userId;
                    $adminName = $this->fetchColumn($sql);
                } else {
                    $this->returnError("权限不足");
                }
                $sql = "select * from system_add_plane where system_id={$systemInfo['id']} and plane_id={$plane['id']} and type=2";
                $system = $this->fetchOne($sql);
                if (!$system) {
                    // 发送短信
//                     $result = $this->sendValidateSmsByInvoice ( $plane['phone'], $validate );
//                    $content = "【飞马机器人】" . $adminName . "希望将" . $uasSerialId . "飞机加入到" . $systemInfo ['system_name'] . "中去，回复TJFJ,添加到该系统中去回T退订";
                    $content = "【飞马机器人】" . $adminName . "希望将" . $uasSerialId . "飞机加入到" . $systemInfo ['system_name'] . "中去，请于" . ($expire/60) . "分钟内回复TJFJ，添加到该系统中去回T退订";
                    $content = "【飞马机器人】" . $adminName . "希望将" . $uasSerialId . "飞机加入到" . $systemInfo ['system_name'] . "中去，请于" . ($expire/60) . "分钟内回复TJFJ，添加到该系统中去";
                    
                    $result = $this->sendSmsContent($plane['phone'], $content);

//                     $result = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
//                     $result = json_decode($result,true);

                    if ($result ['code'] != '0') {
                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($result) . " \r\n", FILE_APPEND);
                        $this->returnResponse(4, $result ['errmsg'], $result);
                    }

                    $foreignId = $this->insert("system_add_plane", array(
                        "user_id" => $user->userId,
                        "system_id" => $systemInfo ['id'],
                        "created_at" => date("Y-m-d H:i:s"),
                        "plane_id" => $plane['id'],
                        "phone" => $plane['phone'],
                        "type" => 2,
                        "status" => 0
                    ));

                    $this->insert("send_sms", array(
                        "user_id" => $user->userId,
                        "sms_id" => $result ['sid'],
                        "ext" => $result['ext'],
                        "phone" => $plane['phone'],
                        "foreign_id" => $foreignId,
                        "content" => $content,
                        "type" => 2
                    ));

                    $this->returnSuccess("发送成功");
                } else if ($system ['status'] == '2') {
                    $this->returnError("飞机已添加");
                } else {
//                     $result = $this->sendValidateSmsByInvoice($plane['phone'], $validate);
                    // $result = $this->sendAddUserValidateSms($phone, $adminName, $systemInfo['system_name']);
//                     $content = "【飞马机器人】" . $adminName . "希望将" . $uasSerialId . "飞机加入到" . $systemInfo ['system_name'] . "中去，回复TJFJ,添加到该系统中去";
//                    $content = "【飞马机器人】" . $adminName . "希望将" . $uasSerialId . "飞机加入到" . $systemInfo ['system_name'] . "中去，回复TJFJ,添加到该系统中去回T退订";
                    $content = "【飞马机器人】" . $adminName . "希望将" . $uasSerialId . "飞机加入到" . $systemInfo ['system_name'] . "中去，请于" . ($expire/60) . "分钟内回复TJFJ，添加到该系统中去回T退订";
                    $content = "【飞马机器人】" . $adminName . "希望将" . $uasSerialId . "飞机加入到" . $systemInfo ['system_name'] . "中去，请于" . ($expire/60) . "分钟内回复TJFJ，添加到该系统中去";
                    $result = $this->sendSmsContent($plane['phone'], $content);

//                     $result = '{"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"13810812238","sid":16822546634}';
//                     $result = json_decode ( $result, true );

                    if ($result ['code'] != '0') {
                        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "yunpian return:" . json_encode($result) . " \r\n", FILE_APPEND);
                        $this->returnResponse(4, $result ['errmsg'], $result);
                    }

                    $this->update("system_add_plane", array(
                        "user_id" => $user->userId,
                        "created_at" => date("Y-m-d H:i:s"),
                        "phone" => $plane['phone'],
                        "receive_at" => null,
                        "status" => 0
                    ), 'id=' . $system ['id']);

                    $this->insert("send_sms", array(
                        "user_id" => $user->userId,
                        "sms_id" => $result ['sid'],
                        "ext" => $result['ext'],
                        "phone" => $plane['phone'],
                        "foreign_id" => $system ['id'],
                        "content" => $content,
                        "type" => 2
                    ));

                    $this->returnSuccess("发送成功");
                }
            } else {
                $this->returnError("已拥有{$systemInfo['plane_limit']}架飞机");
            }
        } else {
            $this->returnError("子系统不存在");
        }

    }

    public function monitorList4PlaneAction()
    {
        $user = $this->getMonitorLoginUser();
        $systemId = $user->subsystemId;
        switch ($this->getRequestAction()) {
            case  $this::REQUEST_ACTION_ADD: {

            };
                break;
            case  $this::REQUEST_ACTION_DELETE: {


                $filterList = json_decode($this->getPost("filter_list"), true);
                $planeId = $filterList["plane_id"];
                if ($planeId && $this->isMonitorSubsystemAdminUser()) {
                    $sql = "delete from bind_plane_system where system_id=$systemId and plane_id=$planeId";
                    $this->execute($sql);
                    $this->returnSuccess("删除成功");
                } else {
                    $this->returnError("删除失败");
                }
            };
                break;
            case  $this::REQUEST_ACTION_UPDATE: {

            };
                break;
            case  $this::REQUEST_ACTION_LIST: {


                $tableName = "(
	SELECT
		p.*, p.type AS cert_type,
		m.name AS plane_model,
		`user`.nickname
	FROM
		plane AS p
	INNER JOIN plane_model AS m ON p.planeModel_id = m.id
	inner JOIN `user` ON p.user_id = `user`.id
	INNER JOIN (
		SELECT
			*
		FROM
			bind_plane_system
		WHERE
			system_id = $systemId
	) AS s ON s.plane_id = p.id
)";
                $this->postQueryByPage(array(
                    "id" => "飞机ID",
                    "uas_serial_id" => "飞机序列号",
                    "plane_model" => "飞机型号",
                    "name" => "持有单位",
                    "company"=>"备注",
                    "phone" => "手机号码",
                    "cert_type" => "证书类型",
                    "expired_at" => "到期时限",
                    "kilometer" => "限制公里数",
                    "key_id" => "钥匙ID"
                ), $tableName, array(
                    ["uas_serial_id", "like", "%", "%"],
                    ["plane_type_id", "=", '', ''],
                    ["phone", "like", "%", "%"],
                    ["cert_type", "=", '', ''],
                    ["expired_at_start", ">=", '', '', "expired_at"],
                    ["expired_at_end", "<=", '', '', "expired_at"],
                    ["key_id", "like", "%", "%"]
                ), " created_at desc ", "id");

            };
                break;
            case  $this->REQUEST_ACTION_DETAIL: {

            };
                break;
        }

        $this->view->setVars(array(
            "planeTypeList" => $this->getPlaneModelInfo(),
            "isSubAdmin"=>($this->isMonitorSubsystemAdminUser()?1:0)

        ));
    }




    public function filedItemChanged($table, $name, $value)
    {

        switch ($name) {

            case "type": {
                switch ($value) {
                    case "0":
                        $value = "通知短信";
                        break;
                    case "1":
                        $value = "申请添加用户";
                        break;
                    case "2":
                        $value = "申请添加飞机";
                        break;
                }
            };
                break;
            case "cert_type": {
                return $value == "1" ? "混合证书" : "无限期";
            };
                break;
            case "status": {
                switch ($value) {
                    case "0": {
                        $value = "等待回复";
                    };
                        break;
                    case "1": {
                        $value = "未知";
                    };
                        break;
                    case "2": {
                        $value = "已通过";
                    };
                        break;
                    case "3": {
                        $value = "已拒绝";
                    };
                        break;
                }
            };
                break;
            case "plane_total":
            case "total": {
                if ($value == null) {
                    return "0";
                }
            };
                break;
            case "name":
            case "company":
            case "phone":
            case "nickname":
            case "system_title":
            case "real_name":
            case "contact_info":
            case "dept_name":
            case "receive_at": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "user_role_id": {
                if ($value == USER_ROLE_SUBSYSTEM_ADMIN) {
                    return "管理员";
                }
                if ($value == USER_ROLE_NORMAL) {
                    return "云用户";
                }
            };
                break;
        }
        return $value;
    }


}